//
//  DZSqlManager.m
//  DaoZiJinFu
//
//  Created by dzjf on 2017/1/11.
//  Copyright © 2017年 dzjf. All rights reserved.
//

#import "DZSqlManager.h"

@implementation DZSqlManager

+ (instancetype)shareInstance {
    static DZSqlManager *manager = nil;
    static dispatch_once_t once;
    dispatch_once(&once, ^{
        
        if (manager == nil)
        {
            manager = [[DZSqlManager alloc]init];
            [manager initWithInformation];
        }
    });
    return manager;
}

- (void)initWithInformation {
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentDirectory = [paths objectAtIndex:0];
    NSString *dbPath = [NSString stringWithFormat:@"%@/JDZUser.db",documentDirectory];
    self.dataBase = [FMDatabase databaseWithPath:dbPath];
    NSLog(@"db==%@",dbPath);
    if (![self.dataBase open])
    {
        NSLog(@"数据库打开失败");
    }
}

- (BOOL)creatNewTable:(NSString *)table {
    [self.dataBase open];
    table = DBBindCard;
    NSString *parma = @"id integer primary key autoincrement,userId text,content text";
    NSString *sqlString = [NSString stringWithFormat:@"create table if not exists %@ (%@)",table,parma];
    BOOL bools = [self.dataBase executeUpdate:sqlString];
    [self.dataBase close];
    return bools;
}

- (BOOL)insertTbaleWithUserId:(NSString *)userId data:(NSDictionary *)data {
    [self.dataBase open];
    NSString *key = @"userId,content";
    NSString *value = [NSString stringWithFormat:@"'%@','%@'",userId,data.mj_JSONString];
    NSString *sqlString = [NSString stringWithFormat:@"insert into %@(%@) values(%@)",DBBindCard,key,value];
    [self.dataBase executeUpdate:sqlString];
    [self.dataBase close];
    return YES;
}

- (id)selectTableWithUserId:(NSString *)userId {
    [self.dataBase open];
    FMResultSet *rs = [self.dataBase executeQuery:[NSString stringWithFormat:@"select * from %@ where userId='%@'",DBBindCard,userId]];
    NSDictionary *data;
    while ([rs next]) {
        NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
        for (NSString *proprty in rs.columnNameToIndexMap) {
            [dictionary setObject:[rs stringForColumn:proprty]?:@"" forKey:proprty];
        }
        data = dictionary;
    }
    NSLog(@"==%@",data);
    if (data) {
        NSDictionary *dic = [DZNetAPI dictionaryWithJsonString:data[@"content"]];
        return dic;
    }
    [self.dataBase close];
    return data;
}

- (BOOL)updateTableWithUserId:(NSString *)userId data:(NSDictionary *)data {
    [self.dataBase open];
    NSString *sqlString = [NSString stringWithFormat:@"update %@ set content='%@' where userId='%@'",DBBindCard,data.mj_JSONString,userId];
    BOOL bools = [self.dataBase executeUpdate:sqlString];
    [self.dataBase close];
    return bools;
}

@end
